/**
 * Created by icyhy on 2017/5/25.
 */
"use strict";
var later = require('later');
var moment = require('moment');
var https = require('https');
var weConfigModel = require('../models/we.config');

function saveAccessToken(accessToken){
  var configEnity = new weConfigModel({
    accesstoken:accessToken,
    created:Date.now()
  });
  console.log(accessToken);
  weConfigModel.create(configEnity, function(err) {
    if (err) console.log(err);
    global.accesstoken = accessToken;
    console.log('accesstoken更新成功');
  });
};

function dotask() {
  var options = {
       hostname: 'api.weixin.qq.com',
       path: '/cgi-bin/token?grant_type=client_credential&appid=' + global.appid + '&secret=' + global.appsecret
  };
  var req = https.get(options, function (res) {
       //console.log("statusCode: ", res.statusCode);
       //console.log("headers: ", res.headers);
       var bodyChunks = '';
       res.on('data', function (chunk) {
             bodyChunks += chunk;
         }).on('end', function () {
             var body = JSON.parse(bodyChunks);
             //console.dir(body);
             if (body.access_token) {
                   var access_token = body.access_token;
                   saveAccessToken(access_token);
                   //console.log(access_token);
               } else {
                   console.dir(body);
               }
         })
   });

  req.on('error', function (e) {
       console.log('ERROR: ' + e.message);
   });
}

module.exports = {
  run:function(){
    //var textSched = later.parse.text('every 1 min');
    var textSched = later.parse.cron('0 0 */1 * *'); //每1小时
    //var textSched = later.parse.text('every 1 hours');

    later.setInterval(dotask, textSched);
    setTimeout(dotask, 100);//fire when app start run
  }
}
